#include "head_c.h"    //头文件要改嗷
//#include <termios.h>     //这个真正整合的时候要给去掉

//禁用终端回显
void disable_echo(){
    struct termios term;
    tcgetattr(STDIN_FILENO,&term);
    term.c_lflag &= ~(ECHO);
    tcsetattr(STDIN_FILENO,TCSANOW,&term);
}

//重新启用终端回显
void enable_echo(){
    struct termios term;
    tcgetattr(STDIN_FILENO,&term);
    term.c_lflag |=ECHO;
    tcsetattr(STDIN_FILENO,TCSANOW,&term);
}


//登录
int login(user_t* status,portocol_t* portocol,int socket_fd){
    char buf[100] = {0};
    printf("请输入用户名：\n");

    //读入用户名，并将用户名的换行符修改为'\0'
    read(STDIN_FILENO,status->user_name,sizeof(status->user_name));
    status->user_name[strlen(status->user_name)-1] = '\0';

    printf("%s\n", status->user_name);
    printf("请输入密码：\n");
    //禁用终端
    disable_echo();
    //读入密码，并将密码的换行符修改为'\0'
    read(STDIN_FILENO,status->password,sizeof(status->password));
    status->password[strlen(status->password)-1] = '\0';


    //重启终端回显
    enable_echo();
    printf("\n");
    printf("%s\n", status->password);

    //添加路径
    sprintf(status->path,"/");
    //存入portocol的结构体
    //portocol->cmd = LOGIN;
    portocol->arg_num = 3;
    sprintf(portocol->arg,"%s&%s&%s", status->user_name,status->path,status->password);
    printf("%s\n", portocol->arg);

    //发送存放用户名和密码的结构体
    send(socket_fd,portocol,sizeof(portocol_t),MSG_NOSIGNAL);

    //接收服务端发回来的确认信息
    //memset(buf,0,sizeof(buf));
    recv(socket_fd,buf,sizeof(buf),0);

    //用户存在
    if(strcmp(buf,"true") == 0){
        //printf("请输入密码：");
        //memset(buf,0,sizeof(buf));

        printf("登录成功！\n");
        status->is_login = true;
        return 0;
    }

    //用户不存在
    else{
        printf("用户名不存在，请注册！\n");
        return 0;
    }
}

//注册
int regist(user_t* status,portocol_t* portocol,int socket_fd){
    char buf[100] = {0};
    printf("请输入要注册的用户名：\n");

    //读入用户名，并将用户名的换行符修改为'\0'
    read(STDIN_FILENO,status->user_name,sizeof(status->user_name));
    status->user_name[strlen(status->user_name)-1] = '\0';

    printf("请输入密码：\n");
    //禁用终端
    disable_echo();

    //读入密码，并将密码的换行符修改为
    read(STDIN_FILENO,status->password,sizeof(status->password));
    status->password[strlen(status->password)-1] = '\0';

    //重启终端回显
    enable_echo();
    printf("\n");

    printf("请再次输入密码：\n");
    //禁用终端
    disable_echo();
    scanf("%s",status->password);
    //重启终端回显
    enable_echo();
    printf("\n");

    sprintf(status->path,"/");

    //存入portocol的结构体
    portocol->cmd = REGISTER;
    portocol->arg_num = 3;
    sprintf(portocol->arg,"%s&%s&%s", status->user_name, status->path, status->password);
    send(socket_fd,portocol,sizeof(portocol_t),MSG_NOSIGNAL);

    //接收服务端发回来的确认信息
    recv(socket_fd,buf,sizeof(buf),0);

    //用户存在
    if(strcmp(buf,"false") == 0){
        //printf("请输入密码：");
        //memset(buf,0,sizeof(buf));

        printf("用户已存在，请重新注册！\n");
        return 0;
    }

    //用户不存在
    else{
        printf("注册成功，已登录！\n");
        status->is_login = true;
        return 0;
    }
}
